﻿using System;
using cz.uhul.DSMLv2;


namespace cz.uhul.DSMLv2.Server.Sql
{




  public static partial class LdRequestServerExtension
  {







    public static LdDeleteResponse Execute(this LdDeleteRequest delReq)
    {
      //return new LdDeleteResponse(LdResultCodeEnum.Unavailable, "not implemented feature", "");

      LdDistinguishedName dn;

      if (!LdDistinguishedName.TryParse(delReq.DistinguishedName, out dn))
        return new LdDeleteResponse(
          LdResultCodeEnum.InvalidDNSyntax
          , "deleteRequest failed"
          , "invalid DistinguishedName:" + delReq.DistinguishedName
        );

      if (string.IsNullOrEmpty(dn))
        return new LdDeleteResponse(
          LdResultCodeEnum.InvalidDNSyntax
          , "deleteRequest failed"
          , "invalid DN:[empty]"
        );

      try
      {
        if (delReq.Controls.Count == 0)
          LdDatabase.DeleteEntry(delReq.DistinguishedName);

        else if (delReq.Controls[0].Type == "1.2.840.113556.1.4.805")
          LdDatabase.DeleteTree(delReq.DistinguishedName);

        else
          return new LdDeleteResponse(
            LdResultCodeEnum.OperationsError
            , "deleteRequest failed for dn=" + delReq.DistinguishedName
            , "invalid operation"
          );

        return new LdDeleteResponse(LdResultCodeEnum.Success, null, null);
      }
      catch (Exception e)
      {
        return new LdDeleteResponse(
          LdResultCodeEnum.OperationsError
          , "deleteRequest failed for dn=" + delReq.DistinguishedName, e.Message
        );
      }
    }



  }

}